<?php

namespace app\admin\controller;
vendor('aliyun-oss-php-sdk-master.autoload');

use OSS\OssClient;
use OSS\Core\OssException;
use app\model\AdminImages as ModelActivityImages;

class Img extends Member
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 上传图片 \n
     * URI : /admin/img.upload
     * @param :
     *  name      | type   | null | description
     * -----------|--------|------|-------------
     *  passport  | string | 必填 | 用户票据
     *  type      | string | 必填 | 图片分类 goods、category、ad
     *  file_data | string | 必填 | 文件名称（不参与签名）
     *
     * @return
     *  name   | type   | description
     * --------|--------|-------------
     *  imgUrl | string | 上传的图片对应的url
     */
    public function uploadImg()
    {
        $str_type = strval($this->_getContentParams('type'));;

        _toCompare(in_array($str_type, ['goods', 'category', 'ad']), '===', false, 10818); // 图片分类不正确

        _toCompare(!isset($_FILES['file_data']['name']), '===', true, 13018);
        _toCompare(!isset($_FILES['file_data']['type']), '===', true, 13018);
        _toCompare(!isset($_FILES['file_data']['tmp_name']), '===', true, 13018);
        _toCompare(!isset($_FILES['file_data']['error']), '===', true, 13018);

        $arr_file = $_FILES['file_data'];

        // 文件名称
        $str_name = $arr_file['name'];
        // 得到文件类型，并且都转化成小写
        $str_type = strtolower(substr($str_name, strrpos($str_name, '.') + 1));
        // 定义允许上传的类型
        $arr_allow_type = array('jpg', 'jpeg', 'gif', 'png');
        // 判断文件类型是否被允许上传
        _toCompare(!in_array($str_type, $arr_allow_type), '===', true, 12085);

        // 判断是否是通过HTTP POST上传的 必须是通过HTTP POST上传的
        _toCompare(!is_uploaded_file($arr_file['tmp_name']), '===', true, 12086);

        // 新的图片名称
        $str_new_name = date('YmdHis') . rand(100000, 999999) . '.' . $str_type;

        $object = config('oss.oss_object') . $str_new_name;

        try {
            $ossClient = new OssClient(config('oss.oss_access_key_id'), config('oss.oss_access_key_secret'), config('oss.oss_endpoint'));  //
            $ossClient->uploadFile(config('oss.oss_bucket'), $object, $arr_file['tmp_name']);
        } catch (OssException $e) {
            _returnError(12087);
        }

        $str_img_url = 'http://' . config('oss.oss_bucket') . '.' . config('oss.oss_endpoint') . '/' . $object;

        $arr_data = [
            'admin_id' => $this->admin_id,
            'group_id' => 0,
            'img_url' => $str_img_url,
            'type' => $str_type,
        ];

        $int_result = ModelActivityImages::getInstance()->toAdd($arr_data);
        _toCompare(($int_result > 0), '===', false, 12087);

        _returnData(['imgUrl' => $str_img_url]);
    }
}
